<template>
  <div class="department-management">
    <!-- 搜索表单 -->
    <div class="search-form">
      <div class="form-row">
        <div class="form-item-inline">
          <label>部门名称</label>
          <el-input
            v-model="searchForm.departmentName"
            placeholder="请输入部门名称"
            clearable
          />
        </div>
<!--         <div class="form-item-inline">
          <label>状态</label>
          <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </div> -->
        <div class="button-group">
          <el-button type="primary" @click="handleSearch" :icon="Search" class="search-btn">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh" class="reset-btn">重置</el-button>
        </div>
      </div>
    </div>

    <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
      <div>
        <el-button type="success" @click="handleAdd" :icon="Plus" class="add-btn">新增部门</el-button>
      </div>
      <div>
        <el-button @click="expandAll" size="small" plain>全部展开</el-button>
        <el-button @click="collapseAll" size="small" plain>全部收缩</el-button>
      </div>
    </div>

    <!-- 部门列表容器 -->
    <div class="department-list-container">
      <!-- 部门列表滚动容器 -->
      <div class="list-scroll-container">
        <!-- 表头 -->
        <div class="list-header">
          <div class="header-item name-col">部门名称</div>
          <!-- <div class="header-item code-col">部门编码</div> -->
          <!-- <div class="header-item parent-col">上级部门</div> -->
          <div class="header-item manager-col">部门负责人</div>
          <!-- <div class="header-item status-col">状态</div> -->
          <div class="header-item date-col">创建时间</div>
          <div class="header-item action-col">操作</div>
        </div>

        <div class="list-content" v-if="paginatedData.length > 0">
          <transition-group name="department-list" tag="div">
            <div
              v-for="(department, index) in paginatedData"
              :key="department.id"
              class="list-item"
              :class="{ [`level-${department.level}`]: true }"
            >
            <div class="list-row">
              <div class="name-col">
                <div class="name-content" :style="{ paddingLeft: (department.level * 24) + 'px' }">
                  <!-- 展开收缩按钮 -->
                  <el-button
                    v-if="department.children && department.children.length > 0"
                    :icon="isExpanded(department.id) ? ArrowDown : ArrowRight"
                    @click="toggleExpand(department.id)"
                    size="small"
                    text
                    class="expand-btn"
                  />
                  <span v-else class="expand-placeholder"></span>

                  <el-icon :size="20" color="#667eea">
                    <OfficeBuilding />
                  </el-icon>
                  <span class="name">{{ department.name }}</span>
                 <!--  <span v-if="department.level > 0" class="level-indicator">
                    ({{ getLevelText(department.level) }})
                  </span> -->
                </div>
              </div>
             <!--  <div class="code-col">
                <span>{{ department.code }}</span>
              </div> -->
           <!--    <div class="parent-col">
                <span>{{ department.parentName || '-' }}</span>
              </div> -->
              <div class="manager-col">
                <span>{{ department.manager || '-' }}</span>
              </div>
             <!--  <div class="status-col">
                <el-tag :type="getStatusTagType(department.status)" size="small">
                  {{ department.status === 'active' ? '启用' : '禁用' }}
                </el-tag>
              </div> -->
              <div class="date-col">
                <span>{{ department.createTime }}</span>
              </div>
              <div class="action-col">
                <div class="action-buttons">
                  <el-button type="primary" size="small" plain @click="handleEdit(department)" style="color: #a685ff; border-color: #a685ff; background-color: #f3f0ff;">编辑</el-button>
                <!--   <el-button
                    :type="department.status === 'active' ? 'warning' : 'success'"
                    size="small"
                    plain
                    @click="handleToggleStatus(department)"
                  >
                    {{ department.status === 'active' ? '禁用' : '启用' }}
                  </el-button> -->
                  <el-button type="danger" size="small" plain @click="handleDelete(department)">删除</el-button>
                </div>
              </div>
            </div>
            </div>
          </transition-group>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <el-empty description="暂无部门数据" />
        </div>
      </div>
    </div>

    <!-- 分页 - 右下角固定 -->
    <div class="pagination-fixed">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="filteredData.length"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
      />
    </div>

    <!-- 部门弹窗组件 -->
    <DepartmentDialog
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :form-data="formData"
      @submit="handleDialogSubmit"
      @cancel="resetForm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, OfficeBuilding, ArrowDown, ArrowRight } from '@element-plus/icons-vue'
import DepartmentDialog from './components/DepartmentDialog.vue'

// 部门数据接口
interface Department {
  id: number
  name: string
  code: string
  parentId?: number
  parentName?: string
  manager?: string
  status: 'active' | 'inactive'
  createTime: string
  description?: string
  children?: Department[]
}

// 搜索表单
const searchForm = ref({
  departmentName: '',
  status: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = ref<Partial<Department>>({})

// 层级部门数据
const departmentTreeData = ref<Department[]>([
  {
    id: 1,
    name: '十一智库科技有限公司',
    code: 'COMP001',
    manager: '总经理',
    status: 'active',
    createTime: '2024-01-01 10:00:00',
    children: [
      {
        id: 2,
        name: '技术部',
        code: 'TECH001',
        parentId: 1,
        manager: '张三',
        status: 'active',
        createTime: '2024-01-15 10:30:00',
        children: [
          {
            id: 3,
            name: '前端组',
            code: 'TECH001-1',
            parentId: 2,
            manager: '李前端',
            status: 'active',
            createTime: '2024-01-20 09:00:00'
          },
          {
            id: 4,
            name: '后端组',
            code: 'TECH001-2',
            parentId: 2,
            manager: '王后端',
            status: 'active',
            createTime: '2024-01-20 09:30:00'
          },
          {
            id: 5,
            name: '测试组',
            code: 'TECH001-3',
            parentId: 2,
            manager: '赵测试',
            status: 'active',
            createTime: '2024-01-20 10:00:00'
          }
        ]
      },
      {
        id: 6,
        name: '产品部',
        code: 'PROD001',
        parentId: 1,
        manager: '李四',
        status: 'active',
        createTime: '2024-01-16 14:20:00',
        children: [
          {
            id: 7,
            name: '产品设计组',
            code: 'PROD001-1',
            parentId: 6,
            manager: '产品经理',
            status: 'active',
            createTime: '2024-01-21 09:00:00'
          },
          {
            id: 8,
            name: 'UI设计组',
            code: 'PROD001-2',
            parentId: 6,
            manager: 'UI设计师',
            status: 'active',
            createTime: '2024-01-21 10:00:00'
          }
        ]
      },
      {
        id: 9,
        name: '运营部',
        code: 'OPS001',
        parentId: 1,
        manager: '运营总监',
        status: 'active',
        createTime: '2024-01-17 09:15:00'
      }
    ]
  }
])

// 展开状态管理
const expandedKeys = ref<Set<number>>(new Set([1])) // 默认展开根节点

// 切换展开状态
const toggleExpand = (departmentId: number) => {
  if (expandedKeys.value.has(departmentId)) {
    expandedKeys.value.delete(departmentId)
  } else {
    expandedKeys.value.add(departmentId)
  }
}

// 检查是否展开
const isExpanded = (departmentId: number) => {
  return expandedKeys.value.has(departmentId)
}

// 将树形数据扁平化为列表，保持层级信息，支持展开收缩
const flattenDepartments = (departments: Department[], level = 0, parentExpanded = true): (Department & { level: number; visible: boolean })[] => {
  const result: (Department & { level: number; visible: boolean })[] = []

  departments.forEach(dept => {
    const visible = parentExpanded
    result.push({ ...dept, level, visible })

    if (dept.children && dept.children.length > 0 && isExpanded(dept.id)) {
      result.push(...flattenDepartments(dept.children, level + 1, visible && isExpanded(dept.id)))
    }
  })

  return result
}

// 扁平化的部门数据用于显示，只显示可见的
const departmentData = computed(() => {
  const flattened = flattenDepartments(departmentTreeData.value)
  return flattened.filter(dept => dept.visible)
})

// 过滤后的数据
const filteredData = computed(() => {
  const filtered = departmentData.value.filter(department => {
    const nameMatch = !searchForm.value.departmentName ||
      department.name.toLowerCase().includes(searchForm.value.departmentName.toLowerCase())
    const statusMatch = !searchForm.value.status || department.status === searchForm.value.status

    return nameMatch && statusMatch
  })

  // 如果有搜索条件，自动展开所有匹配的部门
  if (searchForm.value.departmentName || searchForm.value.status) {
    // 展开所有有匹配子项的父部门
    const expandParents = (departments: typeof departmentTreeData.value) => {
      departments.forEach(dept => {
        if (dept.children) {
          const hasMatchingChild = dept.children.some(child =>
            filtered.some(f => f.id === child.id)
          )
          if (hasMatchingChild) {
            expandedKeys.value.add(dept.id)
          }
          expandParents(dept.children)
        }
      })
    }
    expandParents(departmentTreeData.value)
  }

  return filtered
})

// 分页后的数据
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  return status === 'active' ? 'success' : 'danger'
}

// 获取层级文本
const getLevelText = (level: number) => {
  const levelTexts = ['', '一级部门', '二级部门', '三级部门', '四级部门']
  return levelTexts[level] || `${level}级部门`
}

// 全部展开
const expandAll = () => {
  const getAllIds = (departments: Department[]): number[] => {
    const ids: number[] = []
    departments.forEach(dept => {
      ids.push(dept.id)
      if (dept.children) {
        ids.push(...getAllIds(dept.children))
      }
    })
    return ids
  }

  const allIds = getAllIds(departmentTreeData.value)
  expandedKeys.value = new Set(allIds)
}

// 全部收缩
const collapseAll = () => {
  expandedKeys.value = new Set([1]) // 只保留根节点展开
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  ElMessage.success('搜索完成')
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    departmentName: '',
    status: ''
  }
  currentPage.value = 1
  ElMessage.info('已重置搜索条件')
}

// 新增部门
const handleAdd = () => {
  dialogTitle.value = '新增部门'
  formData.value = {
    name: '',
    code: '',
    manager: '',
    status: 'active'
  }
  dialogVisible.value = true
}

// 编辑部门
const handleEdit = (department: Department) => {
  dialogTitle.value = '编辑部门'
  formData.value = { ...department }
  dialogVisible.value = true
}

// 切换状态
const handleToggleStatus = (department: Department) => {
  const newStatus = department.status === 'active' ? 'inactive' : 'active'
  const action = newStatus === 'active' ? '启用' : '禁用'

  ElMessageBox.confirm(
    `确定要${action}部门"${department.name}"吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    department.status = newStatus
    ElMessage.success(`部门"${department.name}"已${action}`)
  }).catch(() => {
    ElMessage.info('操作已取消')
  })
}

// 删除部门
const handleDelete = (department: Department) => {
  ElMessageBox.confirm(
    `确定要删除部门"${department.name}"吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = departmentData.value.findIndex(d => d.id === department.id)
    if (index > -1) {
      departmentData.value.splice(index, 1)
      ElMessage.success('部门已删除')
    }
  }).catch(() => {
    ElMessage.info('操作已取消')
  })
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 弹窗提交
const handleDialogSubmit = (data: Partial<Department>) => {
  if (data.id) {
    // 编辑
    const index = departmentData.value.findIndex(d => d.id === data.id)
    if (index > -1) {
      departmentData.value[index] = { ...departmentData.value[index], ...data }
      ElMessage.success('部门信息已更新')
    }
  } else {
    // 新增
    const newDepartment: Department = {
      id: Date.now(),
      name: data.name!,
      code: data.code!,
      manager: data.manager,
      status: data.status!,
      createTime: new Date().toLocaleString('zh-CN')
    }
    departmentData.value.unshift(newDepartment)
    ElMessage.success('部门已添加')
  }

  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  formData.value = {}
}

onMounted(() => {
  // 组件挂载时的初始化逻辑
})
</script>

<style scoped>
.department-management {
  padding: 24px;
}

/* 搜索表单样式 - 美化版本 */
.search-form {
  padding: 0 24px 20px 0px;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.form-item-inline {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 200px;
}

.form-item-inline label {
  font-size: 14px;
  font-weight: 600;
  color: #475569;
  white-space: nowrap;
  min-width: 60px;
}

.form-item-inline .el-input,
.form-item-inline .el-select {
  width: 160px;
}

.button-group {
  display: flex;
  gap: 12px;
}

.search-btn {
  background: linear-gradient(90deg, rgb(91, 124, 255) 0%, rgb(166, 133, 255) 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.reset-btn {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border: 1px solid #cbd5e1;
  color: #64748b;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
  transform: translateY(-1px);
}

.add-btn {
  background: linear-gradient(90deg, rgb(91, 124, 255) 0%, rgb(166, 133, 255) 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 部门列表容器样式 */
.department-list-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
  overflow: hidden;
  max-height: 550px;
  display: flex;
  flex-direction: column;
}

/* 列表头部样式 */
.list-header {
  display: flex;
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%);
  border-bottom: 1px solid #c7d2fe;
  padding: 16px 20px;
  font-weight: 600;
  color: #4338ca;
  font-size: 16px;
  position: sticky;
  top: 0;
  z-index: 10;
  min-width: max-content;
}

.header-item {
  display: flex;
  align-items: center;
}

.name-col {
  flex: 1.2;
  min-width: 150px;
}

.code-col {
  flex: 1;
  min-width: 120px;
}

.parent-col {
  flex: 1;
  min-width: 120px;
}

.manager-col {
  flex: 1;
  min-width: 120px;
}

.status-col {
  flex: 0.8;
  min-width: 80px;
}

.date-col {
  flex: 1.2;
  min-width: 160px;
}

.action-col {
  flex: 1.5;
  min-width: 200px;
}

/* 列表滚动容器 */
.list-scroll-container {
  flex: 1;
  overflow-y: auto;
  overflow-x: auto;
}

.list-content {
  background: white;
}

.list-item {
  border-bottom: 1px solid #f1f5f9;
  transition: background-color 0.2s;
}

.list-item:hover {
  background: #f8fafc;
}

.list-item:last-child {
  border-bottom: none;
}

.list-row {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  min-height: 60px;
  min-width: max-content;
}

/* 部门名称列样式 */
.name-content {
  display: flex;
  align-items: center;
  gap: 12px;
  transition: padding-left 0.3s ease;
}

.name {
  font-weight: 500;
  color: #1f2937;
}

.level-indicator {
  font-size: 12px;
  color: #6b7280;
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
}

/* 展开收缩按钮样式 */
.expand-btn {
  width: 24px;
  height: 24px;
  padding: 0;
  margin-right: 8px;
  border: none;
  background: transparent;
  color: #6b7280;
  transition: all 0.2s;
}

.expand-btn:hover {
  background: #f3f4f6;
  color: #374151;
}

.expand-placeholder {
  width: 24px;
  height: 24px;
  margin-right: 8px;
  display: inline-block;
}

/* 动画效果 */
.department-list-enter-active,
.department-list-leave-active {
  transition: all 0.3s ease;
}

.department-list-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}

.department-list-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 层级样式 */
/* .level-0 {
  background: #fafafa;
}

.level-1 {
  background: #f8f9fa;
}

.level-2 {
  background: #f1f3f4;
}
 */
.name {
  font-weight: 500;
  color: #1f2937;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  padding: 4px 12px;
  font-size: 12px;
  border-radius: 6px;
}

/* 空状态样式 */
.empty-state {
  padding: 60px 20px;
  text-align: center;
}

/* 分页样式 - 右下角固定 */
.pagination-fixed {
  position: fixed;
  bottom: 24px;
  right: 24px;
  z-index: 100;
  background: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  border: 1px solid #e5e7eb;
}

.pagination-fixed :deep(.el-pagination) {
  margin: 0;
}

.pagination-fixed :deep(.el-pagination .el-pager li) {
  background: transparent;
  border-radius: 6px;
  margin: 0 2px;
  transition: all 0.2s;
}

.pagination-fixed :deep(.el-pagination .el-pager li:hover) {
  background: #f3f4f6;
}

.pagination-fixed :deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.pagination-fixed :deep(.el-pagination .btn-prev),
.pagination-fixed :deep(.el-pagination .btn-next) {
  border-radius: 6px;
  transition: all 0.2s;
}

.pagination-fixed :deep(.el-pagination .btn-prev:hover),
.pagination-fixed :deep(.el-pagination .btn-next:hover) {
  background: #f3f4f6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .department-management {
    padding: 16px;
  }

  .form-row {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }

  .form-item-inline {
    min-width: auto;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .form-item-inline label {
    min-width: auto;
  }

  .form-item-inline .el-input,
  .form-item-inline .el-select {
    width: 100%;
  }

  .button-group {
    margin-left: 0;
    flex-direction: column;
    gap: 8px;
  }

  .search-btn,
  .reset-btn,
  .add-btn {
    width: 100%;
  }

  .list-header,
  .list-row {
    padding: 12px 16px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }

  .pagination-fixed {
    position: relative;
    bottom: auto;
    right: auto;
    margin-top: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }
}

@media (max-width: 1024px) {
  .form-row {
    gap: 16px;
  }

  .form-item-inline {
    min-width: 180px;
  }

  .form-item-inline .el-input,
  .form-item-inline .el-select {
    width: 140px;
  }

  .button-group {
    flex-wrap: wrap;
  }
}

/* 标签样式优化 */
:deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
}
</style>